﻿using KAKA.Domain;
using KAKA.Repository;
using Morus;
using Morus.Infrastructure;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;

namespace KAKA.Controllers
{
    public abstract class BaseController : Controller
    {
        protected BaseController()
        {
            EventAggregator = IoC.Resolve<IEventAggregator>();
            UserRepository = IoC.Resolve<IUserRepository>();
            DictionaryRepository = IoC.Resolve<IDictionaryRepository>();
            SettingRepository = IoC.Resolve<ISettingRepository>();
            FormsAuthentication = IoC.Resolve<IFormsAuthentication>();
        }

        public IEventAggregator EventAggregator { get; private set; }
        public IUserRepository UserRepository { get; private set; }
        public IDictionaryRepository DictionaryRepository { get; private set; }
        public ISettingRepository SettingRepository { get; private set; }
        public IFormsAuthentication FormsAuthentication { get; private set; }

        public User CurrentUser
        {
            get
            {
                if (User.Identity.IsAuthenticated)
                {
                    return HttpContext.Items[typeof(User)] as User;
                }

                return null;
            }
        }

        public bool IsCurrentUserAuthenticated
        {
            get
            {
                if (HttpContext.User.Identity.IsAuthenticated && (CurrentUser != null))
                {
                    if (!CurrentUser.Lockout)
                    {
                        return true;
                    }

                    Log.Warning("Logging out User: {0}", CurrentUser.Email);

                    // Logout the user if the account is locked out
                    FormsAuthentication.SignOut();

                    Log.Info("User Logged out.");
                }

                return false;
            }
        }

        public string CurrentUserIPAddress
        {
            get
            {
                return HttpContext.Request.UserHostAddress;
            }
        }
    }
}
